package com.apicloud.moduleDemo;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.apicloud.pkg.sdk.R;
import com.google.gson.Gson;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import sdk.pay.PayConstant;
import sdk.pay.PayException;
import sdk.pay.PayExceptionType;
import sdk.pay.PayLogUtil;
import sdk.pay.PayMD5Util;
import sdk.pay.PayTypeModel;
import sdk.pay.PayUtil;
import sdk.pay.PayUtilListener;


public class PayActivity extends Activity implements PayUtilListener {
    private Toast mToast;
    private int mCheckedId = -1;
    private ImageView mOldCheckedView;
    private ListView mPayList;
    private TextView mPayName;
    private TextView mPayPrice;
    private Button mPaySubmit;
    private PayUtil mPayUtil;
    protected Dialog mProgressDialog;
    private boolean isPaying;

    private static final String SYSTEM_NAME = "jft";
    private static final String CODE = "10208331";
    private static final String APPID = "20161111102907658374";
    private static final String COM_KEY = "40F4A509B7459D667B68C9A51A4E14DA";
    private static final String KEY = "1b4f2dd8a284638cf325122bcc69af31";
    private static final String VECTOR = "2995d86414449a62";

    private static final String RETURN_URL = "http://shangjia.jtpay.com/Form/TestReturn";
    private static final String NOTICE_URL = "http://shangjia.jtpay.com/Form/TestNotice";	

    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            dismiss();
            List<PayTypeModel> payTypeModelList = mPayUtil.getPayTypeModels();
            if (payTypeModelList.size() > 0) {
                mPayList.setVisibility(View.VISIBLE);
                PayTypeAdapter adapter = new PayTypeAdapter(PayActivity.this, payTypeModelList);
                mPayList.setAdapter(adapter);
                mPayList.post(new Runnable() {
                    // set default choice
                    @Override
                    public void run() {
                        mOldCheckedView = (ImageView) mPayList.getChildAt(0).findViewById(R.id.ImageButton_junpay_type_Checked);
                        mOldCheckedView.setImageResource(R.drawable.image_icon_radiobutton_yes);
                        mCheckedId = 0;
                    }
                });
            } else {
                mPayList.setVisibility(View.GONE);
                Toast.makeText(PayActivity.this, "Did not get the payment!", Toast.LENGTH_SHORT).show();
            }
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        if (mPayUtil != null && isPaying) {
            mPayUtil.getPayStatus();
        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PayException.getInstance().init(getApplicationContext());
        setContentView(R.layout.pay_layout);
        initWidgets();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String goodsName = bundle.getString("GoodsName");
        String goodsPrice = bundle.getString("GoodsPrice");

        mPayName.setText(goodsName);
        mPayPrice.setText(goodsPrice);
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        mPayUtil = new PayUtil(this);
        getToken();
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismiss();
    }

    private TokenParam getTokenParam() {
        Date date = new Date();
        String p1_usercode = CODE;
        String CompKey = COM_KEY;
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String p2_order = dateFormat.format(date);
        String p3_money = mPayPrice.getText().toString();
        String p4_returnurl = RETURN_URL; //user define
        String p5_notifyurl = NOTICE_URL; //user define
        String p6_ordertime = dateFormat.format(date);
        String p7_sign = PayMD5Util.getMD5(p1_usercode + "&" + p2_order + "&" + p3_money + "&" + p4_returnurl + "&" + p5_notifyurl + "&" + p6_ordertime + CompKey).toUpperCase();
        return new TokenParam(p1_usercode, p2_order, p3_money, p4_returnurl, p5_notifyurl, p6_ordertime, "SDK", p7_sign);
    }

    private void getToken() {
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(PayConstant.TIME_OUT, TimeUnit.SECONDS).readTimeout(PayConstant.TIME_OUT, TimeUnit.SECONDS).build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(PayConstant.PAY_URL).client(client).build();
        APIInterface apiInterface = retrofit.create(APIInterface.class);
        TokenParam tokenParam = getTokenParam();

        Map<String, String> map = new HashMap<String, String>();
        map.put("p1_usercode", tokenParam.getUserCode());
        map.put("p2_order", tokenParam.getOrder());
        map.put("p3_money", tokenParam.getMoney());
        map.put("p4_returnurl", tokenParam.getReturnUrl());
        map.put("p5_notifyurl", tokenParam.getNotifyUrl());
        map.put("p6_ordertime", tokenParam.getOrderTime());
        map.put("p9_paymethod", tokenParam.getMethod());
        map.put("p7_sign", tokenParam.getSign());

        Call<ResponseBody> resultCall =
                apiInterface.getToken(SYSTEM_NAME, map);
        resultCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    String result;
                    try {
                        result = response.body().string();
                        Gson gson = new Gson();
                        ServerResult serverResult = gson.fromJson(result, ServerResult.class);
                        if (serverResult.getFlag().equals("1")) {
                            String token = serverResult.getToken();
                            if (TextUtils.isEmpty(token)) {
                                showToast(getString(R.string.invalid_token));
                            } else {
                                mPayUtil.setToken(token);
                                mPayUtil.setPayParam(APPID, KEY, VECTOR, SYSTEM_NAME);
                                mProgressDialog = ProgressDialog.show(PayActivity.this, "", getString(R.string.init_tips), false, true, null);
                                mPayUtil.getPayType();
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                PayLogUtil.log("getToken onFailure");
            }
        });
    }


    private void initWidgets() {
        mPayName = (TextView) findViewById(R.id.junpay_TextView_name);
        mPayPrice = (TextView) findViewById(R.id.junpay_TextView_price);
        mPayList = (ListView) findViewById(R.id.junpay_listview);
        mPaySubmit = (Button) findViewById(R.id.junpay_button_submit);
        mPaySubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCheckedId >= 0) {
                    mProgressDialog = ProgressDialog.show(PayActivity.this, "", getString(R.string.pay_info), false, true, null);
                    String typeId = getTypeId(mCheckedId);
                    mPayUtil.getPayParam(Integer.parseInt(typeId));
                    isPaying = true;
                } else {
                    Toast.makeText(PayActivity.this, "Payment has not yet chosen", Toast.LENGTH_SHORT).show();
                }
            }
        });
        mPayList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mCheckedId != -1) {
                    mOldCheckedView.setImageResource(R.drawable.image_icon_radiobutton_no);
                }
                mOldCheckedView = (ImageView) view.findViewById(R.id.ImageButton_junpay_type_Checked);
                mOldCheckedView.setImageResource(R.drawable.image_icon_radiobutton_yes);
                mCheckedId = position;
            }
        });
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            PayLogUtil.log("dismiss");
            mProgressDialog.dismiss();
        }
    }

    private void showToast(String str) {
        mToast.setText(str);
        mToast.show();
    }

    @Override
    protected void onDestroy() {
        if (null != mPayUtil) {
            mPayUtil.destroy();
        }
        super.onDestroy();
    }

    private String getTypeId(int index) {
        List<PayTypeModel> list = mPayUtil.getPayTypeModels();
        PayTypeModel model = list.get(index);
        return model.getTypeid();
    }

    @Override
    public void onPayDataResult() {
        runOnUiThread(mRunnable);
    }

    @Override
    public void onPayException(int exceptionType,String exceptionContent) {
        if (null != exceptionContent) {
            showToast(exceptionContent);
        } else {
            PayExceptionType type = PayExceptionType.values()[exceptionType];
            dismiss();
            String str;
            switch (type) {
                case DATA_EXCEPTION: {
                    str = getString(R.string.data_exception);
                    break;
                }
                case ENCRYPT_EXCEPTION: {
                    str = getString(R.string.encrypt_exception);
                    break;
                }
                case GET_PAY_METHOD_FAILED: {
                    str = getString(R.string.get_pay_method_failed);
                    break;
                }
                case DECRYPT_EXCEPTION: {
                    str = getString(R.string.decrypt_exception);
                    break;
                }
                case RETURN_ERROR_DATA: {
                    str = getString(R.string.return_error_data);
                    break;
                }
                case PAY_SYSTEM_ID_EMPTY: {
                    str = getString(R.string.pay_system_id_empty);
                    break;
                }
                case SERVER_CONNECTION_EXCEPTION: {
                    str = getString(R.string.server_connection_exception);
                    break;
                }
                default: {
                    str = "";
                    break;
                }
            }
            showToast(str);
        }
    }

    @Override
    public void onPayProgressDialog() {
        dismiss();
    }

	@Override
	public void onPayStatus(int payStatus, String orderId, String payMoney, String payTime) {
		// TODO Auto-generated method stub
        if (payStatus == 1) {
            showToast(getString(R.string.pay_success));
        } else {
            showToast(getString(R.string.pay_failure));
        }
        isPaying = false;
	}
}